package com.guochenglang.www.util;

import com.guochenglang.www.util.connect.Config;
import com.guochenglang.www.util.error.MyExceptionHandler;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Map;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 判断是否为敏感词
 *
 * @author GuoChenglang
 */
public class DangerWordBoolean {
    /**
     * 敏感词数组
     */
    private static final ArrayList<String> DANGER_WORD = new ArrayList<>();
    /**
     * 敏感词正则
     */
    private static final String REGEX;
    private static final Pattern PATTERN;

    static {
        //读取properties文件，将敏感词放入数组中
        Properties prop = new Properties();
        InputStream inputStream = Config.class.getClassLoader().getResourceAsStream("DangerWord.properties");
        try {
            prop.load(inputStream);
            //将敏感词放入数组
            String[] arrayElements = prop.getProperty("dangerWord").split(",");
            Collections.addAll(DANGER_WORD, arrayElements);
            REGEX = "(?:^|[^\\p{L}])(" + String.join("|", DANGER_WORD) + ")(?:$|[^\\p{L}])";
            PATTERN = Pattern.compile(REGEX);
        } catch (IOException e) {
            MyExceptionHandler.registerHandler();
            throw new RuntimeException(e);
        }
    }

    /**
     * 判断text是否含有敏感词
     *
     * @param text 判断的数据
     * @return 是否含有敏感词
     */
    public static boolean isDangerWord(String text) {
        System.out.println(REGEX);
        Matcher matcher = PATTERN.matcher(text);
        return matcher.find();
    }
}
